package com.deepglint.processfunction;

import com.deepglint.beans.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-23 22:49
 * 使用process将数据输出到侧输出流中
 */
public class ProcessTest_SideOutPutCase {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.getConfig().setAutoWatermarkInterval(200);

        DataStream<String> streamSource = env.socketTextStream("192.168.150.128", 7777);

        DataStream<SensorReading> dataStream = streamSource.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], split[1], new Long(split[2]), new Double(split[3]));
        });

        // TODO ！！！！需要带上{},要不然就会存在类型擦除的问题
        OutputTag<SensorReading> outputTag = new OutputTag<SensorReading>("my_tag") {
        };

        // 将温度大于30的放入侧输出流
        SingleOutputStreamOperator<SensorReading> splitProcess = dataStream.process(new ProcessFunction<SensorReading, SensorReading>() {
            @Override
            public void processElement(SensorReading value, ProcessFunction<SensorReading, SensorReading>.Context ctx, Collector<SensorReading> out) throws Exception {
                if (value.getTemperature() > 30) {
                    ctx.output(outputTag, value);
                } else {
                    out.collect(value);
                }
            }
        });

        splitProcess.getSideOutput(outputTag).print("high");
        splitProcess.print("low");

        env.execute();
    }
}
